﻿using AspNetCoreRateLimit;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Magic.Core;

public static class RateLimitServiceCollectionExtensions
{
    /// <summary>
    /// 限流配置
    /// </summary>
    /// <param name="services"></param>
    /// <param name="configuration"></param>
    /// <returns></returns>
    public static IServiceCollection AddRateLimit(this IServiceCollection services, ConfigurationManager configuration)
    {
        configuration.AddJsonFile($"RateLimitConfig.json", optional: true, reloadOnChange: true);
        //load general configuration from appsettings.json
        services.Configure<ClientRateLimitOptions>(configuration.GetSection("IpRateLimiting"));

        //load ip rules from appsettings.json
        //services.Configure<IpRateLimitPolicies>(configuration.GetSection("IpRateLimitPolicies"));

        // inject counter and rules stores
        services.AddInMemoryRateLimiting();
        //services.AddDistributedRateLimiting<AsyncKeyLockProcessingStrategy>();
        //services.AddDistributedRateLimiting<RedisProcessingStrategy>();
        //services.AddRedisRateLimiting();

        // configuration (resolvers, counter key builders)
        services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
        return services;
    }

    public static async void UseRateLimiting(this WebApplication app)
    {
        app.UseClientRateLimiting();
    }

}
